package com.ophiux.transaction;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @desc: 事务消息生产者
 * @author: hhl
 * @date：2023/8/17 15:30
 */
public class TransactionProducer {

    public static void main(String[] args) throws MQClientException, MQBrokerException, RemotingException, InterruptedException {
        TransactionMQProducer producer = new TransactionMQProducer("TransactionProducer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        //异步提交事务状态，提升性能
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("ExecutorService-hhl");
                return thread;
            }
        });
        producer.setExecutorService(threadPoolExecutor);
        //本地事务监听器
        producer.setTransactionListener(new TransactionListenerImpl());

        producer.start();

        String[] tags = new String[]{"A", "B", "C", "D", "E"};
        for (int i = 0; i < 10; i++) {
            Message message = new Message("Transaction", tags[i % tags.length], (tags[i % tags.length] + "_" + i + "_TransactionProducer").getBytes(StandardCharsets.UTF_8));
            TransactionSendResult transactionSendResult = producer.sendMessageInTransaction(message, null);
            System.out.println(tags[i % tags.length] + "_" + i + "_消息发送成功" + transactionSendResult);
            Thread.sleep(10);
        }
        Thread.sleep(100000);
        producer.shutdown();
    }
}
